package com.uh.checking;

import com.uh.checking.proc.MainJarProcessor;
import com.uh.checking.proc.SubJarProcessor;
import com.uh.checking.proc.SubJarShadeProcessor;
import com.uh.common.test.ClassResourceUtils;
import com.uh.checking.config.ConfigException;
import com.uh.checking.config.JarConfig;
import com.uh.checking.config.SubJarConfig;
import com.uh.checking.config.SubJarShadeConfig;
import org.yaml.snakeyaml.Yaml;
import java.io.*;

import static com.uh.common.test.ClassResourceUtils.loadResourceAsStream;

public class JarCheckingEraser {


    public static void main(String[] args) {

        String configPath = null;

        String workingDir = null;

        for (int i = 0; i < args.length; i++) {
            if ("-f".equalsIgnoreCase(args[i])) {
                if (i + 1 < args.length) {
                    configPath = args[++i];
                } else {
                    usage();
                }
            }
            else if ("-w".equalsIgnoreCase(args[i])) {
                if (i + 1 < args.length) {
                    workingDir = args[++i];
                } else {
                    usage();
                }
            }
            else {
                usage();
            }
        }

        if(configPath == null) {
            usage();
        }


        Yaml yaml = new Yaml();
        JarConfig config = null;
        File configFile = ClassResourceUtils.getResourceFile(configPath);
        if(configFile != null) {
            try(InputStream cpIn = loadResourceAsStream(configPath)) {
                config = yaml.loadAs(cpIn, JarConfig.class);
                System.out.println("Load config file from classpath:" + configPath + " (" + configFile.getAbsolutePath() + ")");
            } catch (IOException e) {
                System.err.println("Load config from classpath error! " + e.getMessage());
            }
        }
        else {
            configFile = new File(configPath);
            if(configFile.exists() && configFile.isFile()) {
                try(FileInputStream fileIn = new FileInputStream(configFile)) {
                    config = yaml.loadAs(fileIn, JarConfig.class);
                    System.out.println("Load config file from file:" + configPath + " (" + configFile.getAbsolutePath() + ")");
                } catch (Exception e) {
                    System.err.println("Load config file error! " + e.getMessage());
                }
            }
            else {
                throw new ConfigException("Failed to found configFile:" + configFile);
            }
        }

        if(workingDir != null) {
            config.setWorkingDir(workingDir);
        }


        System.out.println("===========Checking Eraser Settings============ \n"
                + "configFile=" + configFile + "\n"
                + "workingDirectory=" + config.getWorkingDir() + "\n"
                + "===========End Config File============");

        config.mergeDefaultSubJars();

        MainJarProcessor mainProcessor = new MainJarProcessor(config);

        for(String step : config.getSteps()) {
            switch (step) {
                case "clean":
                    mainProcessor.clean();
                    break;
                case "unzip":
                    mainProcessor.unzipMainJar();
                    break;
                case "process":
                    //File dirLibs = new File(mainProcessor.getUnzipDir(), PATH_LIBS);
                    if(config.getSubJars() != null) {
                        for (SubJarConfig subJarConf : config.getSubJars()) {
                            SubJarProcessor subProcessor = new SubJarProcessor(subJarConf, mainProcessor);
                            subProcessor.process();
                        }
                    }

                    if(config.getSubJarShades() != null) {
                        for (SubJarShadeConfig subShadeConf : config.getSubJarShades()) {
                            SubJarShadeProcessor subShadeprocessor = new SubJarShadeProcessor(subShadeConf, mainProcessor);
                            subShadeprocessor.process();
                        }
                    }
                    break;
                case "zip":
                    mainProcessor.zipMainJar();
                    break;
            }
        }



    }

    /**
     * 判断文件路径是否是绝对路径
     * @param path
     * @return
     */
    public static boolean isAbsolute(String path) {
        return (path.charAt(0) == '/' || path.matches("^[a-zA-Z]{1}:.*"));
    }

//    private static void usage() {
//        System.err.println("Started error! To start it, using:");
//        System.err.println("java com.uh.tools.checking.JarCheckingEraser\n    will load jar-checking.yml in classpath or filepath.");
//        System.err.println("java com.uh.tools.checking.JarCheckingEraser your-config.yml\n    will load your-config.yml in classpath or filepath.");
//    }

    private static void usage() {
        System.err.println("Started error! To start it, using:");
        System.err.println("java -jar checking-eraser.jar -f configFile -w workingDirectory");
        System.exit(1);
    }

}
